<template>
    <basic-layout>
        <a-card style="width: 500px;margin: 150px auto;text-align: center;">
            <!-- 第三方应用头像 -->
            <a-avatar size="large" :src="client['appLogo']" />
            <h3>欢迎使用吃惊账号,登录<span style="color: crimson;"> {{ client['appName'] }} </span></h3>
            <p>
                <span>账号：{{ $store.getters.getMyInfo.username }},</span>
                <router-link :to="{ name : 'logout',query : { callback: encodeURI($route.fullPath) } }">切换账号</router-link>
            </p>
            <!-- 授权列表 -->
            <a-card :title="'\'' + client['appName'] + '\' 将有权访问以下内容'" size="small" style="text-align: left;" :bordered="false">
                <p>1. 您的昵称、头像、性别等信息</p>
            </a-card>
            <a-button size="large" type="primary" block @click="handleSubmit">授权并登录</a-button>
        </a-card>
    </basic-layout>
</template>

<script>
    import { getOauthClient,getGrantCode } from '../apis/index';
    import BasicLayout from '../components/layouts/BasicLayout';
    export default {
        components : { BasicLayout },
        props : {
            clientId : { type : String, required : true }
        },
        data(){
            return {
                client : {},
            };
        },
        mounted() {
            let $this = this;
            //  非空校验
            if (!$this.clientId){
                $this.$modal.error({
                    title : '400',
                    content : '客户端Id不能为空!',
                    //  回到首页
                    onOk : () => $this.$router.push({ path : '/' }).then()
                });
            }
            //  初始化客户端信息
            getOauthClient($this.clientId).then(res => $this.client = res.data);
        },
        methods : {
            handleSubmit : function(e) {
                e.preventDefault();
                let $this = this;
                //  获取授权码
                getGrantCode($this.client['id'])
                    .then(result => {
                        //  获取回调地址,判断是否带有参数
                        let callback = $this.client.callback;
                        callback = callback.indexOf('?') === -1 ? callback + '?' : callback + '&';
                        //  拼接授权码
                        callback += 'code='+ result.data;
                        callback += '&flag='+ $this.$store.getters.getFlag;
                        //  拼接其他参数
                        for (let key in $this.$route.query){
                            callback += '&' + key + '=' + $this.$route.query[key];
                        }
                        //  跳转到回调地址
                        window.location.href = callback;
                    });
            }
        }
    }
</script>
